package com.librarySys.librarySys.Configuration;

import com.librarySys.librarySys.Bean.User;
import com.librarySys.librarySys.myUtil.iPasswordEncoder;
import com.librarySys.librarySys.service.UserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import javax.annotation.Resource;

@Configuration
public class mySpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Resource
    private UserDetailService<User> userDetailService;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailService).passwordEncoder(new iPasswordEncoder());
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // super.configure(http);
        http.csrf().disable().authorizeRequests()
                .antMatchers("/bookList","/","/record","/search").authenticated()
                .antMatchers("/login","/register","/test/**").permitAll()
                .antMatchers("/user/**").hasRole("USER")
                .antMatchers("/manager/**").hasRole("ADMIN")
                .and().formLogin().loginPage("/login").permitAll().defaultSuccessUrl("/bookList");
        http.logout().logoutSuccessUrl("/login");
        http.headers().frameOptions().disable();
    }
    @Override
    public void configure(WebSecurity web) throws Exception {
        // 配置静态文件不需要认证
        web.ignoring().antMatchers("/static/**");
    }

}
